package com.gouwudai.gobbs.dao.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.gouwudai.gobbs.common.IPageList;
import com.gouwudai.gobbs.dao.IUserDAO;
import com.gouwudai.gobbs.pojo.TbbsRule;
import com.gouwudai.gobbs.pojo.TbbsUserDetail;
import com.gouwudai.gobbs.pojo.TbbsUserInfo;
import com.litt.core.common.PageParam;
import com.litt.core.common.Utility;
import com.litt.core.exception.DBException;


public class UserDAOImpl extends BaseDAOImpl implements IUserDAO
{
	private static final Logger logger = Logger.getLogger(UserDAOImpl.class);
	private static final String BUSI_NAME = "用户基本信息";
	
	/**
	 * 根据用户名获得用户信息,逻辑删除的除外
	 * @param userId
	 * @return
	 */
	public TbbsUserInfo load(String loginId) 
	{		
		String hql = "from TbbsUserInfo where loginId='"+loginId+"' and isdelFlag=0";	
		TbbsUserInfo userInfo = (TbbsUserInfo)super.uniqueResultHql(hql);
		
		return userInfo;
	}
	
	/**
	 * 用户详细信息
	 * @param userId
	 * @return
	 * @throws DBException
	 */
	public TbbsUserDetail loadDetail(Integer userId) 
	{
		TbbsUserDetail tbbsUserDetail = (TbbsUserDetail)super.loadObject(TbbsUserDetail.class, userId);
		return tbbsUserDetail;		
	}
	
	/**
	 * 根据用户名获得用户信息
	 * @param userId
	 * @return
	 */
	public TbbsUserInfo load(Integer userId) 
	{			
		TbbsUserInfo userInfo = (TbbsUserInfo)super.loadObject(TbbsUserInfo.class, userId);
		return userInfo;
	}	
	
	/**
	 * 统计该EMAIL是否被注册
	 * @param userId 大于0时过滤该用户
	 * @param email
	 * @return
	 */
	public int countByEmail(int userId,String email) 
	{		
		String hql = "select count(*) from TbbsUserInfo where email='"+email+"' and isdelFlag=0";
		if(userId>0)
			hql = hql+" and userId<>"+userId;
		int count = super.listHqlCount(hql);
		return count;
	}
	
	/**
	 * 统计该loginId是否被注册
	 * @param loginId
	 * @return
	 */
	public int countByLoginId(String loginId) 
	{		
		String hql = "select count(*) from TbbsUserInfo where loginId='"+loginId+"'";	
		int count = super.listHqlCount(hql);
		return count;
	}	
	
	public int saveUserInfo(TbbsUserInfo userInfo) 
	{
		//加密密码
		String md5Pass = Utility.MD5EncodeString(userInfo.getPassword());
		userInfo.setPassword(md5Pass);
		return super.saveObject(userInfo);		
	}
	
	public int saveUserDetail(TbbsUserDetail userDetail) 
	{
		return super.saveObject(userDetail);		
	}	
	
	/**
	 * 更新用户基本信息
	 * @param userInfo
	 */
	public void updateUserInfo(TbbsUserInfo userInfo)
	{
		super.updateObject(userInfo);	
	}
	
	/**
	 * 更新用户详细信息
	 * @param userDetail
	 * @throws DBException
	 */
	public void updateUserDetail(TbbsUserDetail userDetail)
	{
		super.updateObject(userDetail);		
	}	
	
	/**
	 * 后台管理中更新用户信息
	 * @param userInfo
	 */
	public void updateAdmin(TbbsUserInfo userInfo)
	{
	        StringBuilder hql = new StringBuilder("update TbbsUserInfo set userMoney=?");
	        hql.append(",userDeposit=?");
	        hql.append(",userMark=?");
	        hql.append(",userCredit=?");
	        hql.append(",upfileOpenFlag=?");
	        hql.append(",upfileSize=?");
	        hql.append(",gradeId=?");	
	        hql.append(" where userId=?");
	        super.updateObject(hql.toString(), new Object[]{userInfo.getUserMoney(),
                                                    userInfo.getUserDeposit(),
                                                    userInfo.getUserMark(),
                                                    userInfo.getUserCredit(),
                                                    userInfo.getUpfileOpenFlag(),
                                                    userInfo.getUpfileSize(),
                                                    userInfo.getGradeId(),
                                                    userInfo.getUserId()});
	}	
	
	
    /**
     * 重置密码
     * @param password
     * @param userId
     * @throws DBException
     */
    public void updatePassword(String password,Integer userId)
    {
		//加密密码		
		String md5Pass = Utility.MD5EncodeString(password);	
		//---
        String hql = "update TbbsUserInfo set password=? where userId=?";
        super.updateObject(hql, new Object[]{      
        	md5Pass,
        	userId});

    }
    
    /**
     * 修改用户等级
     * @param gradeId
     * @param userId
     * @throws DBException
     */
    public void updateGrade(Integer gradeId,Integer userId)
    {
        String hql = "update TbbsUserInfo set gradeId=? where userId=?";
        super.updateObject(hql, new Object[]{      
        		gradeId,
        		userId});

    }    
    
    /**
     * 更新用户剩余空间.
     * 
     * @param userId
     * @param size
     */
    public void updateUpfileUsedSize(Integer size,Integer userId)
    {		
        String hql = "update TbbsUserInfo set upfileUsedSize=? where userId=?";
        super.updateObject(hql, new Object[]{      
        		size,
        		userId});
    }  
    
    /**
     * 更新用户头像
     * @param userId
     * @param personalPic
     * @throws DBException
     */
    public void updatePersonalPic(String personalPic,Integer userId)
    {		
        String hql = "update TbbsUserInfo set personalPic=? where userId=?";
        super.updateObject(hql, new Object[]{      
        		personalPic,
        		userId});
    }    
    
    /**
     * 逻辑删除用户
     * @param userId
     * @throws DBException
     */
    public void deleteLogic(Integer userId)
    {
        String hql = "update TbbsUserInfo set isdelFlag=1 where userId="+userId;
        super.executeHql(hql);        	
    }
    
    /**
     * 逻辑恢复用户
     * @param userId
     * @throws DBException
     */
    public void doResumeLogic(Integer userId)
    {
        String hql = "update TbbsUserInfo set isdelFlag=0 where userId="+userId;
        super.executeHql(hql);        	
    }     
    
    /**
     * 物理删除用户
     * @param userId
     */
    public void delete(Integer userId)
    {
        super.deleteObject(TbbsUserInfo.class.getName(),"userId",userId);
    }    
    
	/**
	 * 用户登陆更新
	 * @param req
	 */
	public void doLoginUpdate(Integer userId,String loginIp)
	{
	    	//查询用户登陆规则
	    	
	    	TbbsRule rule = (TbbsRule)super.uniqueResultHql("from TbbsRule where ruleCode='R014'");	    	
	    	
	        StringBuilder hql = new StringBuilder("update TbbsUserInfo set lastLoginTime=?");
	        hql.append(",loginTimes=loginTimes+1");
	        hql.append(",lastLoginIp=?");
	        hql.append(",userMoney=userMoney+?");	       
	        hql.append(",userMark=userMark+?");
	        hql.append(",userCredit=userCredit+?");	        
	        hql.append(" where userId=?");
	        super.updateObject(hql.toString(), new Object[]{new Date(),
                                                            loginIp,
                                                            rule.getRuleMoney(),
                                                            rule.getRuleMark(),
                                                            rule.getRuleCredit(),
                                                            userId});
	}	
	
	/**
	 * 
	 * @param lastLoginTime
	 * @param loginIp
	 * @param userId
	 * @throws DBException
	 */
	public void doLogoutUpdate(Date lastLoginTime,String loginIp,Integer userId)
	{
	        StringBuilder hql = new StringBuilder("update TbbsUserInfo set onlineTime=?,lastLoginIp=?");
	        hql.append(" where userId=?");
            super.updateObject(hql.toString(), new Object[]{Utility.getBetweenMinutes(lastLoginTime,new Date()),
                loginIp,userId}); 
	}
	
	/**
	 * 用户浏览过程中更新积分金币等
	 * @param userId 用户ID
	 * @param userMoney 加减金币
	 * @param userMark 加减积分
	 * @param userCredit 加减信誉
	 * @param userDeposit 加减存款
	 */
	public void doBusinessUpdate(Integer userId,BigDecimal userMoney,BigDecimal userMark,BigDecimal userCredit,BigDecimal userDeposit)
	{
	        StringBuilder hql = new StringBuilder("update TbbsUserInfo set userMoney=userMoney+?");
	        hql.append(",userMark=userMark+?");
	        hql.append(",userCredit=userCredit+?");	  
	        hql.append(",userDeposit=userDeposit+?");	 
	        hql.append(" where userId=?");
            super.updateObject(hql.toString(), new Object[]{userMoney,userMark,userCredit,userDeposit,userId});
	}
	
	/**
	 * 金钱帖购买
	 * @param userId
	 * @param userMoney
	 * @throws DBException
	 */
	public void topicBuyUpdate(Integer userId,BigDecimal userMoney)
	{
	        StringBuilder hql = new StringBuilder("update TbbsUserInfo set userMoney=userMoney-?, where userId=?");
            super.updateObject(hql.toString(), new Object[]{userMoney,userId}); 
	}	
	
	/**
	 * 用户发帖或回复后更新各项参数
	 * @param req
	 */
	public void topicNewOrUpdate(Integer userId,BigDecimal userMoney,BigDecimal userMark,BigDecimal userCredit,boolean isRe)
	{
	        StringBuilder hql = new StringBuilder("update TbbsUserInfo ");
	        hql.append("set userMoney=userMoney+?");	       
	        hql.append(",userMark=userMark+?");
	        hql.append(",userCredit=userCredit+?");
	        if(isRe){
	        	hql.append(", userReCount=userReCount+1");				
			}
	        else{
	        	hql.append(", userTopicCount=userTopicCount+1");
	        }
	        hql.append(" where userId=?");
            
            super.updateObject(hql.toString(), new Object[]{userMoney,userMark,userCredit,userId}); 
	}
	
	/**
	 * 查询所有有效用户
	 * @return
	 */
    public List listAllActive()
    { 
    	String hql = "from TbbsUserInfo where isdelFlag=0";
    	return super.listAll(hql);
    }
    
    /**
     * 查询所有不是指定版面黑名单的有效用户.
     * 
     * @param classId 版面ID
     * 
     * @return the list
     */
    public List listAllClassActive(Integer classId)
    { 
        String hql = "from TbbsUserInfo a where a.isdelFlag=0 and a.userId not in (select b.userId from TbbsBlackList b where b.classId="+classId+")";
        return super.listAll(hql);
    } 
    
    /**
     * 查询指定版面黑名单用户.
     * 
     * @param classId 版面ID
     * 
     * @return the list
     */
    public List listAllClassBlack(Integer classId)
    { 
        String hql = "from TbbsUserInfo a where a.isdelFlag=0 and a.userId in (select b.userId from TbbsBlackList b where b.classId="+classId+")";
        return super.listAll(hql);
    }    
    
	/**
	 * 查询所有等级为gradeId的有效用户
	 * @param gradeId
	 * @return
	 */
    public List listAllActiveByGrade(int gradeId)
    { 
    	String hql = "from TbbsUserInfo where isdelFlag=0 and gradeId="+gradeId;
    	return super.listAll(hql);    	
    }
    
	/**
	 * 查询所有等级为gradeIds的有效用户
	 * @param gradeIds
	 * @return
	 */
    public List listAllActiveByGrade(String gradeIds)
    { 
    	String hql = "from TbbsUserInfo where isdelFlag=0 and gradeId in("+gradeIds+")";
    	return super.listAll(hql);    	
    }    
    
	/**
     * 根据参数名查找用户.
     * 
     * @param pageParam 分页查询条件
     * 
     * @return IPageList
     */
    public IPageList listPage(PageParam pageParam)
    {       
    	String loginId = pageParam.getStringCond("loginId");
    	String userName = pageParam.getStringCond("userName");
    	String trueName = pageParam.getStringCond("trueName");
    	String email = pageParam.getStringCond("email");
    	int gradeId = Utility.parseInt(pageParam.getStringCond("userName"));
    	
    	
    	StringBuilder sb = new StringBuilder("SELECT * FROM TbbsUserInfo where 1=1 ");
    	if(!Utility.isEmpty(loginId))
    	{
	    	sb.append(" and LOGIN_ID like '%");
	    	sb.append(loginId);
	    	sb.append("%'");
    	}
    	if(!Utility.isEmpty(userName))
    	{
	    	sb.append(" and USER_NAME like '%");
	    	sb.append(userName);
	    	sb.append("%'");
    	}
    	if(!Utility.isEmpty(trueName))
    	{
	    	sb.append(" and TRUE_NAME like '%");
	    	sb.append(trueName);
	    	sb.append("%'");
    	}
    	if(!Utility.isEmpty(email))
    	{
	    	sb.append(" and EMAIL like '%");
	    	sb.append(email);
	    	sb.append("%'");
    	}
    	if(gradeId>0)
    	{
	    	sb.append(" and GRADE_ID=");
	    	sb.append(gradeId);	    	
    	}     	

    	return  super.listSqlPage(sb.toString(),pageParam.getPageIndex(),pageParam.getPageSize());
    }    
    
    /**
     * 获得用户所在等级的所有权限
     * @param mgId
     * @return
     * @throws DBException
     */
    public List getGradePermission(Integer gradeId)
    {
    	String hql = "select a from TbbsPermission a,TbbsGradePermission b where b.gradeId="+gradeId+" and b.permissionCode=a.permissionCode";
    	return super.listAll(hql);
    }    
}
